#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

char filename[1024];
char temp[1024];

int main(int argc, char* argv[]) {
    if (argc < 4) return 1 + 0 * printf("merge: Completion Project corpus data merger\n\
Merges parts of corpus into one big sorted file\n\
---\n\
Usage: %s <n> <begin> <end>\n\
n -- integer, which n-grams to merge\n\
begin, end -- integers, which parts to merge\n\
---\n\
The file \"out\" will appear in \"<n>-grams\" folder\n", argv[0]);
    int ngrams, begin, end;
    sscanf(argv[1], "%d", &ngrams);
    sscanf(argv[2], "%d", &begin);
    sscanf(argv[3], "%d", &end);
    sprintf(filename, "%dgrams/out", ngrams);
    freopen(filename, "w", stdout);
    vector< pair<long long, char*> > a;
    for (int i = begin; i <= end; i++) {
        sprintf(filename, "%dgrams/%d", ngrams, i);
        freopen(filename, "r", stdin);
        while (gets(temp)) {
            int tab = 0;
            while (temp[tab] != '\t') tab++;
            char* word = new char[tab + 1];
            memcpy(word, temp, tab * sizeof(temp[0]));
            word[tab] = 0;
            long long c;
            sscanf(temp + tab + 1, "%lld", &c);
            a.push_back(make_pair(-c, word));
        }
    }
    sort(a.begin(), a.end());
    for (vector< pair<long long, char*> >::iterator it = a.begin(); it != a.end(); ++it) {
        printf("%11lld %s\n", -it->first, it->second);
    }
    return 0;
}

